/*
 * localStorage 本地存储  是否应该加密？，加个开启加密的开关
 */
const prefix = 'storage_';
const expireTimePrefix = 'expire_';
const storage = {
  //本地存储前缀
  prefix: prefix,
  //本地存储有效期前缀
  expireTimePrefix: expireTimePrefix,
  /*
   *@method 写入存储
   *@param  String name 保存本地的key
   *@param  mix    value 混合类型
   *@param  mix   expire 0永久有效，时间戳为js格式精确到微秒
   *@return
   */
  set(name, value, expire) {
    let keys = this.prefix + name;
    expire = expire > 0 ? expire : 0;
    if (typeof value === 'object') {
      value = JSON.stringify(value)
    }
    this.setExpireTime(name, expire);
    return localStorage.setItem(keys, value);
  },
  /*
   *@method 获取本地存储
   *@param  String name 保存本地的key
   *@return
   */
  get(name) {
    if (this.isExpireTime(name)) {
      return '';
    }
    let keys = this.prefix + name;
    let value = localStorage.getItem(keys)
    if (/^(\{.*\})|(\[.*\])$/.test(value)) value = JSON.parse(value)
    return value
  },
  /*
   *@method 移除本地存储
   *@param  String name 保存本地的key
   *@return
   */
  remove(name) {
    let keys = this.prefix + name;
    this.removeExpireTime(name);
    return localStorage.removeItem(keys)
  },
  /*
   *@method 写入有效期存储
   *@param  String name 保存本地的key
   *@param  mix    value 时间戳/日期
   *@return
   */
  setExpireTime(name, value) {
    let keys = this.prefix + this.expireTimePrefix + name;
    return localStorage.setItem(keys, value);
  },
  /*
   *@method 获取有效期
   *@param  String name 保存本地的key
   *@return
   */
  getExpireTime(name) {
    let keys = this.prefix + this.expireTimePrefix + name;
    let value = localStorage.getItem(keys);
    return value;
  },
  /*
   *@method 移除有效期
   *@param  String name 保存本地的key
   *@return
   */
  removeExpireTime(name) {
    let keys = this.prefix + this.expireTimePrefix + name;
    return localStorage.removeItem(keys);
  },
  /*
   *@method 有效期验证
   *@param  String  name 保存本地的key
   *@param  String
   *@return Boolean false表示未过期  true表示过期
   */
  isExpireTime(name) {
    let expireTime = this.getExpireTime(name);
    let timestamp = (new Date()).getTime();
    if (expireTime > 0 && expireTime < timestamp) {
      return true;
    } else {
      return false;
    }
  },
  /*
   *@method 移除全部本地存储
   *@param  String name 保存本地的key
   *@return
   */
  clear() {
    localStorage.clear();
  }
}

export default storage
